import 'dart:convert';

import 'package:azlistview/azlistview.dart';
import 'package:chat/model/friend_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:lpinyin/lpinyin.dart';

class AddFriendScreen extends StatefulWidget {
  const AddFriendScreen({super.key});

  @override
  _AddFriendScreenState createState() => _AddFriendScreenState();
}

class _AddFriendScreenState extends State<AddFriendScreen> {
  List<Friend> friendList = [];

  @override
  void initState() {
    super.initState();
    loadData();
  }

  void loadData() async {
    //加载联系人列表
    rootBundle.loadString('assets/data/car_models.json').then((value) {
      List list = json.decode(value);
      for (var v in list) {
        friendList.add(Friend.fromJson(v));
      }
      _handleList(friendList);
    });
  }

  void _handleList(List<Friend> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp("[A-Z]").hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = "#";
      }
    }
    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(friendList);
    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(friendList);
    friendList.insert(0, Friend(name: '搜索', tagIndex: '↑'));
    friendList.insert(1, Friend(name: '群聊', tagIndex: '↑'));
    setState(() {});
  }

  Widget customHeader() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: TextField(
        //controller: searchController,
        decoration: InputDecoration(
          hintText: '搜索好友',
          prefixIcon: const Icon(Icons.search),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10),
            borderSide: BorderSide.none,
          ),
          filled: true,
          fillColor: Colors.grey[200],
          contentPadding: const EdgeInsets.symmetric(vertical: 0),
        ),
        onChanged: (value) {
          //controller.searchGroups(value);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        title: Text(
          '好友',
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.black),
        ),
        centerTitle: true,
      ),
      body: Column(
        children: [
          Expanded(
            child: AzListView(
              data: friendList,
              itemCount: friendList.length,
              itemBuilder: (BuildContext context, int index) {
                if (index == 0) {
                  return customHeader();
                } else {
                  Friend friend = friendList[index];
                  return Container(
                    padding: EdgeInsets.symmetric(
                      vertical: 8,
                      horizontal: 16,
                    ), // 调整内边距以接近 ListTile 默认样式
                    child: Row(
                      children: [
                        // Leading 部分（头像/图标）
                        InkWell(
                          onTap: () {
                            if (friend.name == "群聊") {
                              Get.toNamed('/groupListScreen');
                            } else {
                              Get.toNamed('/friendDetailScreen');
                            }
                          },
                          child: Container(
                            width: 36,
                            height: 36,
                            decoration: BoxDecoration(
                              shape: BoxShape.rectangle,
                              borderRadius: BorderRadius.circular(4.0),
                            ),
                            child: Image(
                              image: AssetImage('assets/images/zh-CN-XiaoqiuNeural.png'),
                            ),
                          ),
                        ),
                        SizedBox(width: 16), // 模拟 ListTile 的 leading 和 title 之间的间距
                        // Title 部分
                        InkWell(
                          onTap: () {
                            if (friend.name == "群聊") {
                              Get.toNamed('/groupListScreen');
                            } else {
                              Get.toNamed('/friendChatScreen');
                            }
                          },
                          child: Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start, // 确保子项从顶部开始排列
                              children: [
                                Text(
                                  friend.name,
                                  style: TextStyle(fontSize: 16), // 可选：调整文字样式
                                ),
                                Text(
                                  friend.subTitle ?? "",
                                  style: TextStyle(fontSize: 10, color: Colors.grey), // 可选：调整文字样式
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                }
              },
              physics: BouncingScrollPhysics(),
              susItemBuilder: (BuildContext context, int index) {
                Friend friend = friendList[index];
                if ('↑' == friend.getSuspensionTag()) {
                  return Container();
                }
                return Container(
                  height: 40,
                  width: MediaQuery.of(context).size.width,
                  padding: EdgeInsets.only(left: 16.0),
                  color: Color(0xFFF3F4F5),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    friend.getSuspensionTag(),
                    softWrap: false,
                    style: TextStyle(fontSize: 14.0, color: Color(0xFF666666)),
                  ),
                );
              },
              indexBarData: kIndexBarData,
              indexBarOptions: IndexBarOptions(
                needRebuild: true,
                ignoreDragCancel: true,
                downTextStyle: TextStyle(fontSize: 12, color: Colors.white),
                downItemDecoration: BoxDecoration(shape: BoxShape.circle, color: Colors.green),
                indexHintWidth: 120 / 2,
                indexHintHeight: 100 / 2,
                indexHintDecoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/images/ic_index_bar_bubble_gray.png'),
                    fit: BoxFit.contain,
                  ),
                ),
                indexHintAlignment: Alignment.centerRight,
                indexHintChildAlignment: Alignment(-0.25, 0.0),
                indexHintOffset: Offset(-20, 0),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
